﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UFIDA.U9.Base;
using UFIDA.U9.Base.UserRole;
using UFIDA.U9.Cust.YYD.PlugBE.Dtos;
using UFIDA.U9.Cust.YYD.PlugBE.Public;
using UFIDA.U9.SM.ForecastOrder;
using UFIDA.U9.SM.SO;
using UFIDA.U9.SPR.SalePriceList;
using UFSoft.UBF.Business;
using UFSoft.UBF.Util.DataAccess;

namespace UFIDA.U9.Cust.YYD.PlugBE.ForecastOrderP
{
    public class AfterUpdating : UFSoft.UBF.Eventing.IEventSubscriber
    {
        public void Notify(params object[] args)
        {
            #region 从事件参数中取得当前业务实体													 
            if (args == null || args.Length == 0 || !(args[0] is UFSoft.UBF.Business.EntityEvent))
                return;
            BusinessEntity.EntityKey key = ((UFSoft.UBF.Business.EntityEvent)args[0]).EntityKey;
            if (key == null)
                return;
            var holder = key.GetEntity() as UFIDA.U9.SM.ForecastOrder.ForecastOrder;
            if (holder == null)
                return;
            #endregion

            //提交传
            if (holder.OriginalData.Status == ForecastOrderStatusEnum.Opened && holder.Status == ForecastOrderStatusEnum.Approving)
            {
                //新增
                if (string.IsNullOrEmpty(holder.DescFlexField.PrivateDescSeg1))
                {
                    HttpHelper httpHelper = new HttpHelper();
                    var token = httpHelper.GetOAToken();
                    JsonConfig config = new JsonConfig();
                    httpHelper.URL = config.SelectToken("OA.URL") + "/papi/openapi/api/workflow/core/paService/v1/doCreateRequest";

                    User user = User.Finder.FindByID(Context.LoginUserID);
                    var userinfo = httpHelper.GetOAUserInfo(token, user.Code);

                    OADTO dto = new OADTO();
                    dto.access_token = token;
                    dto.userid = userinfo.Key;
                    dto.workflowId = "1198868412116189262";
                    var formData = new FormData();
                    formData.formId = "1198868412116189185";
                    var dataDetails = new List<DataDetailsItem>();



                    //申请人
                    DataDetailsItem d1 = new DataDetailsItem();
                    d1.dataOptions = new List<DataOptionsItem> {new DataOptionsItem{
                        content = Context.LoginUser,
                        optionId = userinfo.Key,
                        type ="resource"
                    }};
                    d1.dataKey = "sqr";
                    dataDetails.Add(d1);

                    //申请部门
                    DataDetailsItem d2 = new DataDetailsItem();
                    d2.dataOptions = new List<DataOptionsItem> {new DataOptionsItem{
                        content="",
                        optionId= userinfo.Value,
                        type="department"
                    }};
                    d2.dataKey = "sqbm";
                    dataDetails.Add(d2);

                    //推送日期
                    DataDetailsItem d3 = new DataDetailsItem();
                    d3.content = DateTime.Now.Date.ToShortDateString();
                    d3.dataKey = "tsrq";
                    dataDetails.Add(d3);

                    //单据类型
                    DataDetailsItem d4 = new DataDetailsItem();
                    d4.content = holder.DocmentType.Name;
                    d4.dataKey = "djlx";
                    dataDetails.Add(d4);

                    //分类
                    string sql = $@" select dbo.F_GetEnumName('UFIDA.U9.CBO.Enums.DemandCodeEnum','{holder.DemandType.Value}','zh-CN') DemandCodeName";
                    DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out DataSet ds);
                    string DemandCodeName = ds.Tables[0].Rows[0]["DemandCodeName"].ToString();
                    DataDetailsItem d5 = new DataDetailsItem();
                    d5.content = DemandCodeName;
                    d5.dataKey = "fl";
                    dataDetails.Add(d5);

                    //单据日期
                    DataDetailsItem d6 = new DataDetailsItem();
                    d6.content = holder.BusinessDate.ToShortDateString();
                    d6.dataKey = "djrq";
                    dataDetails.Add(d6);

                    //客户名称
                    DataDetailsItem d7 = new DataDetailsItem();
                    d7.content = holder.Customer?.Customer?.Name ?? "";
                    d7.dataKey = "khmc";
                    dataDetails.Add(d7);


                    //流程编号
                    DataDetailsItem d8 = new DataDetailsItem();
                    d8.content = holder.DocNo;
                    d8.dataKey = "lcbh";
                    dataDetails.Add(d8);

                    //计划出货日期
                    DataDetailsItem d9 = new DataDetailsItem();
                    d9.content = holder.ShipPlanDate.ToShortDateString();
                    d9.dataKey = "jhchrq";
                    dataDetails.Add(d9);

                    //业务员
                    var userinfo2 = httpHelper.GetOAUserInfo(token, holder.OrderOperator.Code);
                    DataDetailsItem d10 = new DataDetailsItem();
                    d10.dataOptions = new List<DataOptionsItem> {new DataOptionsItem{
                        content = holder.OrderOperator.Code,
                        optionId = userinfo2.Key,
                        type ="resource"
                    }};
                    d10.dataKey = "ywy";
                    dataDetails.Add(d10);

                    foreach (var line in holder.ForecastOrderLines)
                    {
                        //项目
                        DataDetailsItem it6 = new DataDetailsItem();
                        it6.content = line.Project?.Name??"";
                        it6.dataIndex = line.DocLineNo / 10;
                        it6.dataKey = "xm";
                        it6.subFormId = "1198869541684199427";
                        dataDetails.Add(it6);

                        //客户料号
                        DataDetailsItem it3 = new DataDetailsItem();
                        it3.content = line.CustItemCode;
                        it3.dataIndex = line.DocLineNo / 10;
                        it3.dataKey = "khlh";
                        it3.subFormId = "1198869541684199427";
                        dataDetails.Add(it3);

                        //料号
                        DataDetailsItem it1 = new DataDetailsItem();
                        it1.content = line.ItemInfo.ItemID.Code;
                        it1.dataIndex = line.DocLineNo / 10;
                        it1.dataKey = "lh";
                        it1.subFormId = "1198869541684199427";
                        dataDetails.Add(it1);

                        //参考料号
                        DataDetailsItem it2 = new DataDetailsItem();
                        it2.content = line.ItemInfo.ItemID.Code1;
                        it2.dataIndex = line.DocLineNo / 10;
                        it2.dataKey = "cklh";
                        it2.subFormId = "1198869541684199427";
                        dataDetails.Add(it2);


                        //品名
                        DataDetailsItem it4 = new DataDetailsItem();
                        it4.content = line.ItemInfo.ItemID.Name;
                        it4.dataIndex = line.DocLineNo / 10;
                        it4.dataKey = "pm";
                        it4.subFormId = "1198869541684199427";
                        dataDetails.Add(it4);

                        //数量
                        DataDetailsItem it5 = new DataDetailsItem();
                        it5.content = line.Num.ToString();
                        it5.dataIndex = line.DocLineNo / 10;
                        it5.dataKey = "sl";
                        it5.subFormId = "1198869541684199427";
                        dataDetails.Add(it5);

                        //单位
                        DataDetailsItem it8 = new DataDetailsItem();
                        it8.content = line.TU.Name;
                        it8.dataIndex = line.DocLineNo / 10;
                        it8.dataKey = "dw";
                        it8.subFormId = "1198869541684199427";
                        dataDetails.Add(it8);

                        //计划出货日期
                        DataDetailsItem it9 = new DataDetailsItem();
                        it9.content = line.ShipPlanDate.ToShortDateString();
                        it9.dataIndex = line.DocLineNo / 10;
                        it9.dataKey = "jhchrq";
                        it9.subFormId = "1198869541684199427";
                        dataDetails.Add(it9);

                  
                    }

                    formData.dataDetails = dataDetails;
                    dto.formData = formData;
                    dto.otherParams = new OtherParams { isnextflow = "1" };
                    httpHelper.Content = JsonConvert.SerializeObject(dto);
                    var result = JObject.Parse(httpHelper.HttpPosts("POST"));
                    if (result["message"]["errmsg"].ToString() != "success")
                    {
                        throw new Exception(result["message"]["errmsg"].ToString());
                    }

                    holder.DescFlexField.PrivateDescSeg1 = result["message"]["requestId"].ToString();
                }
                else
                {
                    HttpHelper httpHelper = new HttpHelper();
                    var token = httpHelper.GetOAToken();
                    JsonConfig config = new JsonConfig();
                    httpHelper.URL = config.SelectToken("OA.URL") + "/papi/openapi/api/workflow/core/paService/v1/submitRequest";

                    User user = User.Finder.FindByID(Context.LoginUserID);
                    var userinfo = httpHelper.GetOAUserInfo(token, user.Code);

                    OAUpdateDTO dto = new OAUpdateDTO();
                    dto.access_token = token;
                    dto.userid = userinfo.Key;
                    dto.requestId = holder.DescFlexField.PrivateDescSeg1;
                    var formData = new FormData();
                    formData.formId = "1198868412116189185";
                    var dataDetails = new List<DataDetailsItem>();


                    //申请人
                    DataDetailsItem d1 = new DataDetailsItem();
                    d1.dataOptions = new List<DataOptionsItem> {new DataOptionsItem{
                        content = Context.LoginUser,
                        optionId = userinfo.Key,
                        type ="resource"
                    }};
                    d1.dataKey = "sqr";
                    dataDetails.Add(d1);

                    //申请部门
                    DataDetailsItem d2 = new DataDetailsItem();
                    d2.dataOptions = new List<DataOptionsItem> {new DataOptionsItem{
                        content="",
                        optionId= userinfo.Value,
                        type="department"
                    }};
                    d2.dataKey = "sqbm";
                    dataDetails.Add(d2);

                    //推送日期
                    DataDetailsItem d3 = new DataDetailsItem();
                    d3.content = DateTime.Now.Date.ToShortDateString();
                    d3.dataKey = "tsrq";
                    dataDetails.Add(d3);

                    //单据类型
                    DataDetailsItem d4 = new DataDetailsItem();
                    d4.content = holder.DocmentType.Name;
                    d4.dataKey = "djlx";
                    dataDetails.Add(d4);

                    //分类
                    string sql = $@" select dbo.F_GetEnumName('UFIDA.U9.CBO.Enums.DemandCodeEnum','{holder.DemandType.Value}','zh-CN') DemandCodeName";
                    DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out DataSet ds);
                    string DemandCodeName = ds.Tables[0].Rows[0]["DemandCodeName"].ToString();
                    DataDetailsItem d5 = new DataDetailsItem();
                    d5.content = DemandCodeName;
                    d5.dataKey = "fl";
                    dataDetails.Add(d5);

                    //单据日期
                    DataDetailsItem d6 = new DataDetailsItem();
                    d6.content = holder.BusinessDate.ToShortDateString();
                    d6.dataKey = "djrq";
                    dataDetails.Add(d6);

                    //客户名称
                    DataDetailsItem d7 = new DataDetailsItem();
                    d7.content = holder.Customer?.Customer?.Name ?? "";
                    d7.dataKey = "khmc";
                    dataDetails.Add(d7);


                    //流程编号
                    DataDetailsItem d8 = new DataDetailsItem();
                    d8.content = holder.DocNo;
                    d8.dataKey = "lcbh";
                    dataDetails.Add(d8);

                    //计划出货日期
                    DataDetailsItem d9 = new DataDetailsItem();
                    d9.content = holder.ShipPlanDate.ToShortDateString();
                    d9.dataKey = "jhchrq";
                    dataDetails.Add(d9);

                    //业务员
                    var userinfo2 = httpHelper.GetOAUserInfo(token, holder.OrderOperator.Code);
                    DataDetailsItem d10 = new DataDetailsItem();
                    d10.dataOptions = new List<DataOptionsItem> {new DataOptionsItem{
                        content = holder.OrderOperator.Code,
                        optionId = userinfo2.Key,
                        type ="resource"
                    }};
                    d10.dataKey = "ywy";
                    dataDetails.Add(d10);

                    foreach (var line in holder.ForecastOrderLines)
                    {
                        //项目
                        DataDetailsItem it6 = new DataDetailsItem();
                        it6.content = line.Project.Name;
                        it6.dataIndex = line.DocLineNo / 10;
                        it6.dataKey = "xm";
                        it6.subFormId = "1198869541684199427";
                        dataDetails.Add(it6);

                        //客户料号
                        DataDetailsItem it3 = new DataDetailsItem();
                        it3.content = line.CustItemCode;
                        it3.dataIndex = line.DocLineNo / 10;
                        it3.dataKey = "khlh";
                        it3.subFormId = "1198869541684199427";
                        dataDetails.Add(it3);

                        //料号
                        DataDetailsItem it1 = new DataDetailsItem();
                        it1.content = line.ItemInfo.ItemID.Code;
                        it1.dataIndex = line.DocLineNo / 10;
                        it1.dataKey = "lh";
                        it1.subFormId = "1198869541684199427";
                        dataDetails.Add(it1);

                        //参考料号
                        DataDetailsItem it2 = new DataDetailsItem();
                        it2.content = line.ItemInfo.ItemID.Code1;
                        it2.dataIndex = line.DocLineNo / 10;
                        it2.dataKey = "cklh";
                        it2.subFormId = "1198869541684199427";
                        dataDetails.Add(it2);


                        //品名
                        DataDetailsItem it4 = new DataDetailsItem();
                        it4.content = line.ItemInfo.ItemID.Name;
                        it4.dataIndex = line.DocLineNo / 10;
                        it4.dataKey = "pm";
                        it4.subFormId = "1198869541684199427";
                        dataDetails.Add(it4);

                        //数量
                        DataDetailsItem it5 = new DataDetailsItem();
                        it5.content = line.Num.ToString();
                        it5.dataIndex = line.DocLineNo / 10;
                        it5.dataKey = "sl";
                        it5.subFormId = "1198869541684199427";
                        dataDetails.Add(it5);

                        //单位
                        DataDetailsItem it8 = new DataDetailsItem();
                        it8.content = line.TU.Name;
                        it8.dataIndex = line.DocLineNo / 10;
                        it8.dataKey = "dw";
                        it8.subFormId = "1198869541684199427";
                        dataDetails.Add(it8);

                        //计划出货日期
                        DataDetailsItem it9 = new DataDetailsItem();
                        it9.content = line.ShipPlanDate.ToShortDateString();
                        it9.dataIndex = line.DocLineNo / 10;
                        it9.dataKey = "jhchrq";
                        it9.subFormId = "1198869541684199427";
                        dataDetails.Add(it9);


                    }

                    formData.dataDetails = dataDetails;
                    dto.formData = formData;
                    //dto.otherParams = new OtherParams2() ;
                    var Content = JsonConvert.SerializeObject(dto);
                    httpHelper.Content = Content.Remove(Content.Length - 2, 2) + @" },""seniorFormParam"": {""subFormMatchFields"": { ""1198869541684199427"": {""cover"": true,""subFormMatchMore"": ""ZERO"",""subFormNoMatch"": ""ADD""}}}, ""isNewFormData"": true}";
                    var result = JObject.Parse(httpHelper.HttpPosts("POST"));
                    if (result["message"]["errmsg"].ToString() != "success")
                    {
                        throw new Exception(result["message"]["errmsg"].ToString());
                    }
                }
              
            }
        }
    }
}
